<template>
  <div class="main-content order-list-wrapper">
    <div class="filter-box">
      <p class="title">收益账单</p>
      <el-form
        :inline="true"
        :model="form">
        <div class="item">
          <el-form-item label="账单时间">
            <!-- 账单时间 -->
            <el-date-picker
              v-model="form.date"
              type="daterange"
              range-separator="至"
              value-format="YYYY-MM-DD"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDate" />
          </el-form-item>
          <el-form-item label="客户类型">
            <el-select v-model="form.userType" clearable placeholder="请选择">
              <el-option label="直客" value="CUSTOMER" />
              <el-option label="伙伴" value="PARTNER" />
            </el-select>
          </el-form-item>
          <el-form-item class="item-name">
            <el-input
              v-model="form.nickname"
              placeholder="搜索伙伴或客户名称"
              clearable
              @clear="searchFn"
               />
          </el-form-item>
          <div class="top-box">
            <el-button
              type="primary"
              @click="searchFn">
              查询
            </el-button>
          </div>
          &nbsp;
          <div class="top-box">
            <el-button
              type=""
              @click="resetFn">
              重置
            </el-button>
          </div>
          &nbsp;
          <div class="top-box">
            <el-button
              type="primary"
              @click="exportFn">
              导出Excel
            </el-button>
          </div>
       
      
          
        </div>

        
      </el-form>
    </div>
    <div class="content-box">

      
      <ct-table :options="tableOptions">
        <template v-slot:index="scope">
          <span>{{ scope.row.index }}</span>
        </template>
        <template v-slot:orderType="scope">
          <span>{{ scope.row.orderType === 1 ? '续费' : '新购' }}</span>
        </template>
        <template v-slot:isSend="scope">
          <span>{{ scope.row.isSend === 0 ? '否' : '是' }}</span>
        </template>
        <template v-slot:status="scope">
          <span>{{ handleStatus(scope.row.status) }}</span>
        </template>
        <template v-slot:operate="scope">
          <el-text
            type="primary"
            @click="toDetail(scope.row)">
            详情
          </el-text>
        </template>
      </ct-table>

      <ct-pagination
        :options="pageOptions"
        :pageEvent="getBillRecordList">
      </ct-pagination>
    </div>
  </div>
</template>

<script setup>
import { getBillRecord } from '@/api/index';
import axios from 'axios';

import { useRouter } from 'vue-router';
const router = useRouter();

const { proxy } = getCurrentInstance();

import CtTable from '@/components/CtTable.vue';
import CtPagination from '@/components/Pagination.vue';

import { usePageOptions } from '@/hooks/usePageOptions';
const { pageOptions } = usePageOptions();


let form = ref({
  nickname: '',
  productType: '',
  payStyle: '',
  orderSn: '', 
  date: '',
  start: '',
  end: '',
  trainMoney:"",
  inferMoney:"",
  totalMoney:"",
  memberNum:"",
  dateTime:"",
  userType:""
});

function toDetail(row) {
  console.log(row);
  router.push({
    name: 'RevenueDetail',
    query: {
      id: row.id
    }
  });
}

let tableOptions = reactive({
  data: [],
  loading: false,
  columns: [
    {
      label: '序号',
      prop: 'index',
      width: 80,
      isCustom: true
    },
    {
      label: '资金划拨单号',
      prop: 'bizId'
    },
    {
      label: '客户类型',
      prop: 'userType'
    },
    {
      label: '伙伴/客户名称',
      prop: 'nickname'
    },
    {
      label: '本次划拨折扣',
      prop: 'userDiscountRatio'
    },
    {
      label: '用户本次充值',
      prop: 'userRecharge'
    },
    {
      label: '划拨额度',
      prop: 'userVoucherTotal'
    },
    {
      label: '收益',
      prop: 'income'
    },
    {
      label: '划拨状态',
      prop: 'state', 
    },
    {
      label: '账单时间',
      prop: 'createdAt'
    }
  ]
});

function handleStatus(status) {
  const obj = {
    '-1': '已取消',
    0: '待支付',
    1: '已支付',
    2: '已退款'
  };

  return obj[status] || '';
}

function getBillRecordList() {
  tableOptions.loading = true;
  const { currentPage, pageSize } = pageOptions;
  const { nickname, userType,start, end,} = form.value;

  getBillRecord({
    endTime:end,
    nickname,
    page: currentPage ,
    pageSize,
    startTime:start,
    userType
  })
    .then(res => {
      const { content, totalElements } = res.data; 
      if (content.length) {
        for (let i = 0; i < content.length; i++) {
          content[i].index = proxy.$handleIndex(i, pageOptions);
        }
      }
      tableOptions.data = content;
      tableOptions.loading = false;
      pageOptions.total = totalElements;   
    })
    .catch(() => {
      tableOptions.loading = false;
    });
}

const searchFn = proxy.$debounce(() => {
  tableOptions.data = [];
  pageOptions.currentPage = 1;
  pageOptions.total = 0;

  getBillRecordList();
});
function exportFn() {
  const { currentPage, pageSize } = pageOptions;
  const { nickname, userType,start, end,} = form.value;

  axios({
    url: '/api/v2/exportIncome',
    params: {
      nickname,
      startTime:start,
      endTime:end,
      userType,
      page:currentPage,
      pageSize:pageSize,
    },
    headers: {
      token: localStorage.getItem('token')
    },
    responseType: 'blob'
  })
    .then(res => {
      if (res.status === 200) {
        const content = res.data;
        const blob = new Blob([content], {
          // 下载的文件格式自己在这边更改type的值就好了
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });

        const date = new Date();
        const year = date.getFullYear();
        let month = date.getMonth() + 1;
        month = month < 10 ? '0' + month : month;
        let day = date.getDate();
        day = day < 10 ? '0' + day : day;
        let hour = date.getHours();
        hour = hour < 10 ? '0' + hour : hour;
        let minute = date.getMinutes();
        minute = minute < 10 ? '0' + minute : minute;
        let second = date.getSeconds();
        second = second < 10 ? '0' + second : second;
        const filename = `收益账单_${year}${month}${day}${hour}${minute}${second}.xls`;

        const elink = document.createElement('a');
        elink.download = filename;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        ElMessage.error('导出失败，请稍后重试');
      }
    })
    .catch(r => {
      console.error('导出失败---', r);
    });
}
function changeDate(value) {
  if (value) {
    form.value.start = value[0] + ' 00:00:00';
    form.value.end = value[1] + ' 23:59:59';
  } else {
    form.value.start = '';
    form.value.end = '';
  }
  // console.log(value);
  searchFn();
}
// 重置
function resetFn() {
  form.value.start = '';
  form.value.end = '';
  form.value.type = '';
  form.value.status = '';
  form.value.keyword = '';
  searchFn();
}
onMounted(() => {
  getBillRecordList(); 
});
</script>

<style lang="scss" scoped>
.order-list-wrapper {
}
.heard {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 88px;
  border-bottom: 1px solid #ccc;
  padding-bottom: 60px;
  .title {
    margin: 0 !important;
  }
  .Lastime {
    display: flex;
    align-items: center;
    .Biime {
      display: flex;
      align-items: center;
    }
    p {
      color: #888;
      font-size: 12px;
      margin-right: 10px;
    }
  }
}
.el-form {
  .item {
    display: flex;
    align-items: center;

    .el-select {
      width: 192px;
    }

    .el-input {
      width: 192px;
    }
  }
}
.produtype {
  p {
    font-size: 12px;
    color: #888;
    width: 200px;
    text-align: center;
  }
}
.Specific {
  margin-top: 20px;
  padding-bottom: 50px;
  p {
    width: 200px;
    text-align: center;
    font-size: 18px;
  }
}
.top-box{
  margin-top: -20px;
}
.item-name{
  margin-left: -20px;
}
</style>
